package com.zzyl.intercept;

import com.zzyl.constant.Constants;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.UserThreadLocalUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Value("${zzyl.framework.jwt.base64-encoded-secret-key}")
    private String secretKey;
    /**
     * controller方法执行之前进行token校验
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 判断请求是否是后端controller方法的请求 如果不是则放行(css/js/html)
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //2. 获取请求头中的token
        String token = request.getHeader(Constants.USER_TOKEN);
        //3. 判断是否为空 如果为空则返回401
        if(ObjectUtil.isEmpty(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //4. 校验token 如果校验失败 则返回401
        Claims claims = JwtUtil.parseJWT(secretKey, token);
        if(null == claims){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //5. 获取token中的id 如果id为空 则返回401
        Object id = claims.get("id");
        if(ObjectUtil.isEmpty(id)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //6. 向当前线程的副本对象ThreadLocal中存储用户id
        UserThreadLocalUtils.setUserId(id.toString());

        //7. 放行
        return true;
    }

    /**
     * controller执行只有 清楚当前线程的副本数据
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocalUtils.removeUserId();
    }
}
